import {Component, OnInit, Output, EventEmitter, ViewChild, Input, OnChanges, SimpleChanges, NgZone} from '@angular/core';
import {IonInfiniteScroll, LoadingController} from '@ionic/angular';

@Component({
    selector: 'orhon-rolling',
    templateUrl: './rolling.component.html',
    styleUrls: ['./rolling.component.scss'],
})
export class RollingComponent implements OnInit, OnChanges {
    @Input() loading: string;
    @Output() dataUpdate: EventEmitter<string> = new EventEmitter<string>();
    @Output() clear: EventEmitter<any> = new EventEmitter<any>();
    @ViewChild(IonInfiniteScroll, {static: true}) infiniteScroll: IonInfiniteScroll;
    @ViewChild('refresher', {static: true}) refresher;
    @ViewChild('infinite', {static: true}) infinite;
    status: string;

    constructor(private zone: NgZone) {
        this.status = '';
    }

    doRefresh() {
        this.dataUpdate.emit('drop');
        this.common();
    }

    loadData() {
        this.dataUpdate.emit('pull');
        this.common();
    }

    common() {
        this.status = '';
    }

    ngOnInit() {
    }

    async ngOnChanges(changes: SimpleChanges) {
        const loading = changes.loading.currentValue;
        if (changes.loading && loading) {
            if (loading === 'drop') {
                await this.refresher.complete();
            }
            if (loading === 'pull') {
                await this.infinite.complete();
            }
            if (loading === 'noMore') {
                await this.infinite.complete();
                this.status = 'noMore';
            }
            if (loading === 'noData') {
                this.status = 'noData';
            }
            if (loading === 'loading') {
                this.status = 'loading';
            }
            await this.clear.emit();
        }
    }
}
